<!-- 搜索表单 :inline="true" label-width="70px"-->
<template id="search-warpper">
  <el-card
    ref="search-card"
    class="card-box"
    shadow="never"
    :body-style="{ padding: '20px 0px 0px' }"
  >
    <el-form
      v-show="isCollapse"
      ref="search-form"
      :model="formData"
      v-bind="$attrs"
      size="small"
    >
      <el-row style="position:relative;">
        <!--自有品牌-->
        <el-col v-if="isBrand" :span="searchPanel.colSpan">
          <el-form-item
            key="brands"
            prop="brands"
            label="自有品牌:"
            label-width="70px"
          >
            <multiple-selector
              v-model="formData.brands"
              :options="bandOptions"
              placeholder="全部"
            />
          </el-form-item>
        </el-col>
        <!--业态选项-->
        <el-col v-if="isBusinessCategory" :span="searchPanel.colSpan">
          <el-form-item
            key="businessCategories"
            prop="businessCategories"
            label="业态:"
            label-width="70px"
          >
            <multiple-selector
              v-model="formData.businessCategories"
              :options="businessOptions"
              placeholder="全部"
            />
          </el-form-item>
        </el-col>
        <!--大区选项-->
        <el-col :span="searchPanel.colSpan">
          <el-form-item
            key="regions"
            prop="regions"
            label="大区:"
            label-width="70px"
          >
            <multiple-selector
              v-model="formData.regions"
              :options="regionsOPtions"
              placeholder="全部"
            />
          </el-form-item>
        </el-col>
        <!--城市选项-->
        <el-col :span="searchPanel.colSpan">
          <el-form-item
            key="cities"
            prop="cities"
            label="城市:"
            label-width="70px"
          >
            <multiple-selector
              v-model="formData.cities"
              :options="citiesOptions"
              placeholder="全部"
            />
          </el-form-item>
        </el-col>
        <!--门店选项-->
        <el-col v-if="isStore" :span="searchPanel.colSpan">
          <el-form-item
            key="stores"
            prop="stores"
            label="门店:"
            label-width="70px"
          >
            <multiple-selector
              v-model="formData.stores"
              :options="storesOptions"
              placeholder="全部"
            />
          </el-form-item>
        </el-col>
        <!--部门选项-->
        <el-col :span="searchPanel.colSpan">
          <el-form-item
            key="goodsCategoriesOne"
            prop="goodsCategoriesOne"
            label="部门:"
            label-width="70px"
          >
            <multiple-selector
              v-model="formData.goodsCategoriesOne"
              :options="goodsCategoriesOne"
              placeholder="全部"
              @change="onChangeCategories('TWO')"
            />
          </el-form-item>
        </el-col>
        <!--大类选项-->
        <el-col :span="searchPanel.colSpan">
          <el-form-item
            key="goodsCategoriesTwo"
            prop="goodsCategoriesTwo"
            label="大类:"
            label-width="70px"
          >
            <multiple-selector
              v-model="formData.goodsCategoriesTwo"
              :options="goodsCategoriesTwo"
              placeholder="全部"
              @change="onChangeCategories('THREE')"
            />
          </el-form-item>
        </el-col>
        <!--中类选项-->
        <el-col :span="searchPanel.colSpan">
          <el-form-item
            key="goodsCategoriesThree"
            prop="goodsCategoriesThree"
            label="中类:"
            label-width="70px"
          >
            <multiple-selector
              v-model="formData.goodsCategoriesThree"
              :options="goodsCategoriesThree"
              placeholder="全部"
              @change="onChangeCategories('FOUR')"
            />
          </el-form-item>
        </el-col>
        <!--小类选项-->
        <el-col :span="searchPanel.colSpan">
          <el-form-item
            key="goodsCategoriesFour"
            prop="goodsCategoriesFour"
            label="小类:"
            label-width="70px"
          >
            <multiple-selector
              v-model="formData.goodsCategoriesFour"
              :options="goodsCategoriesFour"
              placeholder="全部"
            />
          </el-form-item>
        </el-col>
        <!--商品参数-->
        <template v-if="isGoods">
          <el-col :span="searchPanel.colSpan">
            <el-form-item
              key="commodity"
              prop="commodity"
              label="商品代码:"
              label-width="70px"
            >
              <el-input v-model="formData.commodity" placeholder="请输入商品代码" />
            </el-form-item>
          </el-col>
          <el-col :span="searchPanel.colSpan">
            <el-form-item
              key="commodityName"
              prop="commodityName"
              label="商品名称:"
              label-width="70px"
            >
              <el-input v-model="formData.commodityName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
        </template>
        <!--日期种类选项-->
        <el-col v-if="isDateSwitch" :span="searchPanel.colSpan">
          <el-form-item key="date" label="日期:" label-width="70px">
            <el-select
              v-model="formData.dateType"
              :clearable="false"
              placeholder="请选择日历种类"
              style="width:100%;"
            >
              <el-option key="MONTH" :value="1" label="月版" />
              <el-option key="WEEK" :value="2" label="周版" />
              <el-option
                v-if="isHaveYear"
                key="YEAR"
                :value="3"
                label="年至今"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!--日历插件选项-->
        <el-col
          v-show="formData.dateType !== 3"
          :xs="20"
          :span="searchPanel.colSpan"
        >
          <el-form-item
            key="date"
            :label="isDateSwitch ? '' : '日期:'"
            :label-width="isDateSwitch ? '20px' : '70px'"
          >
            <template v-if="isSingleDate">
              <el-date-picker
                v-model="formData.date"
                :picker-options="pickerOptions"
                style="width:100%;"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
              />
            </template>
            <template v-else>
              <multiple-date-picker
                v-model="dateRange"
                :calendar-type="formData.dateType"
                :shor-curs="shorCur"
              />
            </template>
          </el-form-item>
        </el-col>
        <!--操作项-->
        <div class="form-operate">
          <el-form-item size="small">
            <el-button
              v-debounce="onSumitFrom"
              type="primary"
              class="btn"
              icon="el-icon-search"
              :disabled="disabled"
            >查询</el-button>
            <el-button
              v-debounce="onResetForm"
              type="default"
              icon="el-icon-refresh-right"
              class="btn"
            >重置</el-button>
            <template v-if="isExport">
              <!-- 两种选项风格 expdrop=true-->
              <multiple-download
                v-if="$attrs.expdrop"
                :loading="$attrs.exporting"
                @onExport="onExportFile"
              />
              <!-- 默认导出按钮风格 -->
              <el-button
                v-else
                v-debounce="onExportFile"
                type="success"
                class="btn"
                icon="el-icon-download"
                :loading="$attrs.exporting"
              >
                导出报表
              </el-button>
            </template>
            <template v-if="isExportBottom">
              <multiple-download-bottom
                v-if="$attrs.expdrop"
                :api="exportBottomApi"
                :form-data="formData"
                :loading="$attrs.exporting"
              />
            </template>
          </el-form-item>
        </div>
      </el-row>
    </el-form>
    <div class="search-footer" @click="onChangeCollapse">
      <i
        :class="[
          isCollapse ? 'el-icon-caret-top' : 'el-icon-caret-bottom',
          'collapse-title'
        ]"
      />
      {{ isCollapse ? "收起面板" : "展开面板" }}
    </div>
  </el-card>
</template>
<script>
import { debounce } from 'lodash';
import { getDictList, getCommodityDictList } from '@/api/commonApi';
import MultipleSelector from '@/components/common/MultipleSelector';
import MultipleDatePicker from '@/components/common/MultipleDatePicker';
import MultipleDownload from '@/components/common/MultipleDownload';
import MultipleDownloadBottom from '../MultipleDownloadBottom';

export default {
  components: {
    MultipleSelector,
    MultipleDatePicker,
    MultipleDownload,
    MultipleDownloadBottom
  },
  props: {
    // 是否是零销售报表
    // eslint-disable-next-line vue/require-prop-type-constructor
    isZeroTab: false,
    // 报表类型
    reportType: {
      type: String,
      default: ''
    },
    // 是否业态选项
    isBusinessCategory: {
      type: Boolean,
      default: true
    },
    // 是否需要门店选项
    isStore: {
      type: Boolean,
      default: true
    },
    // 是否需要自有品牌
    isBrand: {
      type: Boolean,
      default: false
    },
    // 是否需要日期切换
    isDateSwitch: {
      type: Boolean,
      default: false
    },
    // 是否需要初始化数据
    isInitData: {
      type: Boolean,
      default: false
    },
    // 是否商品参数
    isGoods: {
      type: Boolean,
      default: false
    },
    // 是否需要年至今
    isHaveYear: {
      type: Boolean,
      default: false
    },
    // 是否只需要日期选项，不用范围
    isSingleDate: {
      type: Boolean,
      default: false
    },
    // 是否需要导出按钮
    isExport: {
      type: Boolean,
      default: true
    },
    // 是否需要导出底表按钮
    isExportBottom: {
      type: Boolean,
      default: false
    },
    // 导出底表api: 使用导出底表按钮时必传
    exportBottomApi: {
      type: Function,
      default: () => {}
    },
    // 时间快捷建
    shorCur: {
      type: Object,
      default: () => ({})
    }
  },
  inject: ['getSearchPanel', 'countTableHeght'],
  data() {
    return {
      size: 'small',
      disabled: false,
      isCollapse: true,
      dateRange: [], // 日期选项
      businessOptions: [], // 业务态选项
      regionsOPtions: [], // 大区选项
      citiesOptions: [], // 城市选项
      storesOptions: [], // 店铺选项
      bandOptions: [], // 自有品牌
      goodsCategories: [],
      goodsCategoriesOne: [],
      goodsCategoriesTwo: [],
      goodsCategoriesThree: [],
      goodsCategoriesFour: [],
      // 表单参数
      formData: {
        date: '',
        department: [],
        businessCategories: [],
        dateType: this.isDateSwitch ? 1 : 0, // 默认0 1-月版，2-周版
        dateBegin: undefined,
        dateEnd: undefined,
        cities: [],
        goodsCategories: [],
        brands: [],
        commodityTypeLevel: 'ONE',
        goodsCategoriesOne: [],
        goodsCategoriesTwo: [],
        goodsCategoriesThree: [],
        goodsCategoriesFour: [],
        regions: [],
        stores: [],
        commodityName: '',
        commodity: ''
      },
      pickerOptions: {}
    };
  },
  computed: {
    searchPanel() {
      return this.getSearchPanel();
    }
  },
  watch: {
    searchPanel: {
      deep: true,
      handler(val) {
        this.isCollapse = val.collapse;
        this.$nextTick(() => this.countSearchPanelHeight());
      }
    },
    // 业态类型级联接口查询
    'formData.businessCategories': {
      deep: true,
      handler(businessCategories) {
        this.onSearchCitiesByBusinessCategory({
          that: this,
          businessCategories
        });
      }
    },
    // 大区级联接口查询
    'formData.regions': {
      deep: true,
      handler(regions) {
        this.onSelectedRegions({ that: this, regions });
      }
    },
    // 城市级联接口查询
    'formData.cities': {
      deep: true,
      handler(cities) {
        if (!this.isStore) return;
        this.onSelectedCities({ that: this, cities });
      }
    },
    // 日期类型切换，初始化时间展示
    'formData.dateType'() {
      this.initDateStr();
    },
    /* 时间变更判断结合业务需求 */
    dateRange: {
      deep: true,
      handler(range) {
        const [dateBegin = '', dateEnd = ''] = range || ['', ''];
        let message = '';
        const countDays = ((dateEnd, dateBegin) => key =>
          this.moment(dateEnd).diff(this.moment(dateBegin), key))(
          dateEnd,
          dateBegin
        );
        if (!this.isDateSwitch && countDays('days') > 730) {
          message = '日期区间不能超过730天,请您重新选择!';
        } else if (
          this.isDateSwitch &&
          this.formData.dateType === 1 &&
          countDays('months') > 23
        ) {
          message = '日期区间不能超过24个月,请您重新选择!';
        } else if (
          this.isDateSwitch &&
          this.formData.dateType === 2 &&
          countDays('weeks') > 103
        ) {
          message = '日期区间不能超过104个周,请您重新选择!';
        }
        if (message) {
          this.disabled = true;
          return this.msgError(message);
        }
        this.disabled = false;
        this.formData.dateBegin = dateBegin;
        this.formData.dateEnd = dateEnd;
      }
    }
  },
  created() {
    // 单项日期选项
    if (this.isSingleDate) {
      this.pickerOptions.disabledDate = (time) => {
        // 限制今天、未来选项
        const limtDay = time >= this.moment().subtract(1, 'days');
        // 限制两年的选项
        const limtYear = time <= this.moment().subtract(2, 'year');
        return limtDay || limtYear;
      };
    }
    this.initDateStr(); // 初始化日期
    this.initOptions(); // 初始化下拉框
  },
  mounted() {
    // 初始化时，是否需要请求接口加载数据
    this.$nextTick(() => {
      if (this.isInitData) this.$emit('submit', this.formData);
    });
  },
  methods: {
    // 初始化所有选项
    initOptions() {
      const params = {
        type: 'BUSINESS_CATEGORY_DICT'
      };
      if (this.isZeroTab) {
        params.businessCategories = ['1', '2', '6'];
      }
      const fetchBusiness = this.onFetchDict(params); // 获取商品分类
      const fetchRegions = this.onFetchDict({ type: 'REGION_DICT' }); // 获取大区
      const fetchCities = this.onFetchDict({ type: 'CITY_DICT' }); // 获取城市
      const fetchStores = this.onFetchDict({ type: 'STORE_DICT' }); // 获取店铺
      const fetchBrand = this.onFetchDict({ type: 'BRAND_DICT' }); // 获取自有品牌
      // 获取各级商品种类的接口
      const fetchCategoriesOne = this.onFetchCategoriesDict({ level: 'ONE' });
      const fetchCategoriesTwo = this.onFetchCategoriesDict({ level: 'TWO' });
      const fetchCategoriesThree = this.onFetchCategoriesDict({
        level: 'THREE'
      });
      const fetchCategoriesFour = this.onFetchCategoriesDict({ level: 'FOUR' });
      // 赋值操作
      Promise.all([
        fetchBusiness,
        fetchRegions,
        fetchCities,
        fetchStores,
        fetchBrand,
        fetchCategoriesOne,
        fetchCategoriesTwo,
        fetchCategoriesThree,
        fetchCategoriesFour
      ])
        .then(reslut => {
          [
            this.businessOptions = [],
            this.regionsOPtions = [],
            this.citiesOptions = [],
            this.storesOptions = [],
            this.bandOptions = [],
            this.goodsCategoriesOne = [],
            this.goodsCategoriesTwo = [],
            this.goodsCategoriesThree = [],
            this.goodsCategoriesFour = []
          ] = reslut || [];
        })
        .catch(error => console.log(error));
    },
    // 结合业务逻辑，初始化日历显示
    initDateStr() {
      const yesterday = this.moment(new Date())
        .subtract(1, 'day')
        .format('YYYY-MM-DD');
      if (this.isSingleDate) return (this.formData.date = yesterday);

      this.formData.dateEnd = yesterday; // 前一天

      if (this.formData.dateType === 0) {
        // 一个月前
        this.formData.dateBegin = this.moment(new Date())
          .subtract(30, 'day')
          .format('YYYY-MM-DD');
      } else if (this.formData.dateType === 1) {
        // 12个月前
        this.formData.dateBegin = this.moment(new Date())
          .subtract(6, 'months')
          .format('YYYY-MM-DD');
        this.formData.dateEnd = this.moment(new Date())
          .subtract(1, 'months')
          .format('YYYY-MM-DD');
      } else if (this.formData.dateType === 2) {
        // 12个周前,默认展示从当前周/月开始向前12周/月，即趋势图有12个数据坐标
        const prevWeek = this.moment().week() - 1;
        this.formData.dateBegin = this.moment()
          .week(prevWeek - 26)
          .startOf('week')
          .format('YYYY-MM-DD');
        this.formData.dateEnd = this.moment().week(prevWeek)
          .endOf('week')
          .format('YYYY-MM-DD'); // 本周周日
      }
      this.$set(this.dateRange, 0, this.formData.dateBegin);
      this.$set(this.dateRange, 1, this.formData.dateEnd);
    },
    // 防抖查询城市与商店选项
    onSelectedRegions: debounce(({ that, regions = [] }) => {
      that.formData.cities = undefined;
      that.formData.stores = undefined;
      const { businessCategories } = that.formData;
      const getCities = that.onFetchDict({ type: 'CITY_DICT', regions });
      const getStores = that.onFetchDict({
        type: 'STORE_DICT',
        regions,
        businessCategories
      });
      Promise.all([getCities, getStores]).then(
        ([citiesOptions = [], storesOptions = []]) => {
          that.citiesOptions = citiesOptions;
          that.storesOptions = storesOptions;
        }
      );
    }, 800),
    // 防抖查询城市下的
    onSelectedCities: debounce(({ that, cities = [] }) => {
      const { regions, businessCategories } = that.formData;
      that.formData.stores = undefined;
      that
        .onFetchDict({
          type: 'STORE_DICT',
          cities,
          regions,
          businessCategories
        })
        .then(storesOptions => {
          that.storesOptions = storesOptions;
        });
    }, 800),
    // 防抖查询业态下的门店
    onSearchCitiesByBusinessCategory: debounce(
      ({ that, businessCategories = [] }) => {
        const { cities, regions } = that.formData;
        that.formData.stores = undefined;
        that
          .onFetchDict({
            type: 'STORE_DICT',
            cities,
            regions,
            businessCategories
          })
          .then(storesOptions => {
            that.storesOptions = storesOptions;
          });
      },
      800
    ),
    // 更改下拉框联动查询
    onChangeCategories(level) {
      this.onFetchCategoriesOptions({ that: this, level });
    },
    // 防抖查询商品分类接口
    onFetchCategoriesOptions: debounce(({ that, level }) => {
      const fetchCategories = level =>
        that.onFetchCategoriesDict({ ...that.formData, level });
      switch (level) {
        case 'TWO':
          that.formData.goodsCategoriesTwo = [];
          that.formData.goodsCategoriesThree = [];
          that.formData.goodsCategoriesFour = [];
          that.$nextTick(async () => {
            that.goodsCategoriesTwo = await fetchCategories('TWO');
            that.goodsCategoriesThree = await fetchCategories('THREE');
            that.goodsCategoriesFour = await fetchCategories('FOUR');
          });
          break;
        case 'THREE':
          that.formData.goodsCategoriesThree = [];
          that.formData.goodsCategoriesFour = [];
          that.$nextTick(async () => {
            that.goodsCategoriesThree = await fetchCategories('THREE');
            that.goodsCategoriesFour = await fetchCategories('FOUR');
          });
          break;
        case 'FOUR':
          that.formData.goodsCategoriesFour = [];
          that.$nextTick(async () => {
            that.goodsCategoriesFour = await fetchCategories('FOUR');
          });
      }
    }, 800),
    // 字典接口
    onFetchDict({
      businessCategories = [],
      type = '',
      cities = [],
      regions = []
    } = {}) {
      return new Promise((resolve, reject) => {
        getDictList({
          businessCategories,
          type,
          cities,
          regions,
          reportType: this.reportType
        }).then(({ data, resultCode, resultMessage }) => {
          if (resultCode === '0000' && data) {
            resolve(data);
          } else {
            reject(resultMessage);
          }
        });
      });
    },
    // 商品类型级别字典
    onFetchCategoriesDict({
      goodsCategoriesOne = [],
      goodsCategoriesTwo = [],
      goodsCategoriesThree = [],
      goodsCategoriesFour = [],
      level = 'ONE'
    } = {}) {
      return new Promise((resolve, reject) => {
        getCommodityDictList({
          goodsCategoriesOne,
          goodsCategoriesTwo,
          goodsCategoriesThree,
          goodsCategoriesFour,
          level
        }).then(({ data, resultCode, resultMessage }) => {
          if (resultCode === '0000' && data) {
            resolve(data);
          } else {
            reject(resultMessage);
          }
        });
      });
    },
    onChangeCollapse() {
      this.isCollapse = !this.isCollapse;
      this.$nextTick(() => this.countSearchPanelHeight());
    },
    countSearchPanelHeight() {
      const cardHeight = this.$refs['search-card'].$el.clientHeight;
      this.countTableHeght(cardHeight);
    },
    // 提交表单
    onSumitFrom() {
      const self = this;
      this.$refs['search-form'].validate(valid => {
        if (valid) this.$emit('submit', self.formData);
      });
    },
    // 重置表单
    onResetForm() {
      this.$refs['search-form'].resetFields(null);
      this.formData.dateType = this.isDateSwitch ? 2 : 0;
      this.initDateStr(); // 初始化日期
      this.initOptions(); // 初始化下拉框
      this.$nextTick(() => {
        this.$emit('reset', this.formData);
      });
    },
    onExportFile(downType) {
      this.$emit('export', { ...this.formData, downType });
    }
  }
};
</script>
<style lang="scss" scoped>
.file-link {
  // color:#fff;
  font-size: 14px;
  margin-top: -4px;
}
.card-box {
  // position: relative;
  border-radius: 0px;
  border: none !important;

  .form-operate {
    display: block;
    float: right;
    .btn {
      display: inline-block;
      padding: 9px 12px;
    }
    .btn-dropdown {
      margin-left: 10px;
    }
  }
  .search-footer {
    position: relative;
    height: 20px;
    box-sizing: border-box;
    background-color: #fff;
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
    text-align: center;
    color: #d3dce6;
    cursor: pointer;
    top: -10px;
  }
  .search-footer:hover {
    color: #409eff;
  }
}
.card-box::after {
  content: "";
  display: inline-block;
  width: 100%;
  height: 1px;
  position: absolute;
  background: #eee;
  left: 0;
  // top: 50%;
}
.text-content {
  font-size: 14px;
  color: #606266;
}

.separator {
  display: inline-block;
  width: 4%;
  text-align: center;
}
.ant-calendar-week-number {
  .ant-calendar-disabled-cell.ant-calendar-selected-day
    .ant-calendar-date:before {
    left: -1px;
    width: 34px;
    background: transparent;
  }
  .ant-calendar-disabled-cell .ant-calendar-date {
    color: rgba(0, 0, 0, 0.25) !important;
    background: #f5f5f5 !important;
  }
}
.el-date-range-picker__content .el-date-range-picker__header div {
  cursor: auto;
}
</style>
